﻿using Abp.AspNetCore.Dependency;
using Abp.Dependency;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Quartz;
using SportsPlatform.Global;
using SportsPlatform.Web.Host.FrameworkQuartz;
using System.IO;

namespace SportsPlatform.Web.Host.Startup
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        internal static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    #region 配置文件热加载、热更新

                    var config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddCommandLine(args)
                      .Build();
                    webBuilder.UseConfiguration(config).UseStartup<Startup>();

                    #endregion
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    #region SQL文件热加载、热更新

                    var basePath = Directory.GetCurrentDirectory();
                    var directory = Path.Join(basePath, "SqlConfig");
                    var files = Directory.GetFiles(directory, "*.config", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        config.AddXmlFile(file, optional: true, reloadOnChange: true);
                    }

                    #endregion
                })
                .UseCastleWindsor(IocManager.Instance.IocContainer)
                .ConfigureServices((hostContext, services) =>
                {
                    #region 注册框架Quartz作业

                    services.AddQuartz(q =>
                    {
                        q.UseMicrosoftDependencyInjectionJobFactory();

                        // Register the job, loading the schedule from configuration
                        q.AddJobAndTrigger<UldAdminFrameworkJob>(hostContext.Configuration);
                    });

                    services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

                    #endregion
                });

    }
}
